package top.yongyan0624.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.web.bind.annotation.*;

import top.yongyan0624.common.lang.Result;
import top.yongyan0624.entity.GoodsGroup;
import top.yongyan0624.entity.StoreCart;
import top.yongyan0624.entity.StoreCartGroup;

import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yongyan
 * @since 2021-09-14
 */
@RestController
@RequestMapping("/store/cart/group")
public class StoreCartGroupController extends BaseController {
    @PostMapping("/modify")
    public Result modify(@RequestBody StoreCartGroup cart) {

        HashMap<String, Long> map = new HashMap<>();
        map.put("user_id", cart.getUserId());
        map.put("goods_id", cart.getGoodsId());

        storeCartGroupService.saveOrUpdate(cart, new UpdateWrapper<StoreCartGroup>().allEq(map));

        GoodsGroup goodsGroup = goodsGroupService.getById(cart.getGoodsId());

        goodsGroup.setUser(sysUserService.getById(goodsGroup.getUserId()));
        goodsGroup.setImgList(StrUtil.split(goodsGroup.getImg(), ',' ,true,true));

        cart.setGoods(goodsGroup);

        return Result.success(cart);
    }

    @GetMapping("/show/{id}")
    public Result show(@PathVariable("id") Long userId) {
        List<StoreCartGroup> cartList = storeCartGroupService.list(new QueryWrapper<StoreCartGroup>().eq("user_id", userId).gt("amount", 0));

        cartList.forEach(c -> {
            GoodsGroup goodsGroup = goodsGroupService.getById(c.getGoodsId());

            goodsGroup.setUser(sysUserService.getById(goodsGroup.getUserId()));
            goodsGroup.setImgList(StrUtil.split(goodsGroup.getImg(), ',' ,true,true));

            c.setGoods(goodsGroup);
        });

        return Result.success(cartList);
    }
}
